package com.rd.p2p.app;


import java.io.IOException;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;

import com.google.protobuf.TextFormat.ParseException;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.model.AppOauthTokenModel;
import com.qdlc.p2p.biz.service.TokenStoreService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.dto.TokenStore;
import com.qdlc.p2p.dal.dto.User;

public class AppOauthTokenAction extends BaseAction<AppOauthTokenModel> implements ModelDriven<AppOauthTokenModel>{
	
	private static final Logger logger = Logger.getLogger(AppOauthTokenAction.class);
	
	@Resource
	private UserService userService;
	
	@Resource
	private TokenStoreService tokenStoreService;
	
	@Resource
	private Map<String,Object> data;
	
	/**
	 * 登录授权
	 * @throws Exception
	 */
	@Action("/app/token/init")
	public void init() throws Exception{
		// 校验参数有效性
		data = model.validAppLogin();
		if(StringUtil.isBlank(data)){
			// 业务处理
			User user = userService.loginForApp(model.getUserName(), model.getPwd());
			if(user == null){
				logger.info("-----------------用户为空，userName："+model.getUserName());
			} else {
				logger.info("-----------------用户id："+user.getUserId());
			}
			data = model.validUser(user);
			if(StringUtil.isBlank(data)){
				session.put(Constant.SESSION_USER, user);
				data = model.tokenInitResponse(user);
				printJson(getStringOfJpaObj(data));
			}else{
				printJson(getStringOfJpaObj(data));
			}
		} else {
			printJson(getStringOfJpaObj(data));
		}
	}
	
	/**
	 * 替换授权
	 * @throws IOException
	 * @throws ParseException 
	 */
	@Action(value="/app/token/refresh")
	public void refresh() throws Exception {
		data = model.validRefreshToken();
		if(StringUtil.isBlank(data)){
			TokenStore tokenStore = tokenStoreService.findByRefreshToken(model.getRefreshToken());
			data = model.tokenRefreshResponse(tokenStore);
			printJson(getStringOfJpaObj(data));
		} else {
			printJson(getStringOfJpaObj(data));
		}
	}
}
